package cn.piggy.gateway.sdk.domain.service;

import cn.piggy.gateway.sdk.exception.GatewayException;
import cn.piggy.gateway.sdk.common.Result;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GatewayCenterService {

    private final Logger logger = LoggerFactory.getLogger(GatewayCenterService.class);

    public void doRegisterApplication(String address, String systemId, String systemName, String systemType, String systemRegistry, String systemAddress) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);
        paramMap.put("systemName", systemName);
        paramMap.put("systemType", systemType);
        paramMap.put("systemRegistry", systemRegistry);
        paramMap.put("systemAddress", systemAddress);
        String resultStr;
        try {
            resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplication", paramMap, 2000);
        } catch (Exception e) {
            logger.error("应用服务注册异常，链接资源不可用：{}", address + "/wg/admin/register/registerApplication");
            throw e;
        }
        Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() {});
        logger.info("向网关中心注册应用服务 systemId：{} systemName：{} 注册结果：{}", systemId, systemName, resultStr);
        if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode()))
            throw new GatewayException("注册应用服务异常 [systemId：" + systemId + "] 、[systemRegistry：" + systemRegistry + "]");
    }

    public void doRegisterApplicationInterface(String address, String systemId, String interfaceId, String interfaceName, String interfaceVersion) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);
        paramMap.put("interfaceId", interfaceId);
        paramMap.put("interfaceName", interfaceName);
        paramMap.put("interfaceVersion", interfaceVersion);
        String resultStr;
        try {
            resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplicationInterface", paramMap, 5000);
        } catch (Exception e) {
            logger.error("应用服务接口注册异常，链接资源不可用：{}", address + "/wg/admin/register/registerApplicationInterface");
            throw e;
        }
        Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() {});
        logger.info("向网关中心注册应用接口服务 systemId：{} interfaceId：{} interfaceName：{} 注册结果：{}", systemId, interfaceId, interfaceName, resultStr);
        if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode()))
            throw new GatewayException("向网关中心注册应用接口服务异常 [systemId：" + systemId + "] 、[interfaceId：" + interfaceId + "]");
    }

    public void doRegisterApplicationInterfaceMethod(String address, String systemId, String interfaceId,
                                                     String methodId, String methodType, String parameterType,
                                                     String parameterName, String uri, String httpCommandType,
                                                     Integer auth,String role) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);
        paramMap.put("interfaceId", interfaceId);
        paramMap.put("methodId", methodId);
        paramMap.put("methodType", methodType);
        paramMap.put("parameterType", parameterType);
        paramMap.put("parameterName", parameterName);
        paramMap.put("uri", uri);
        paramMap.put("httpCommandType", httpCommandType);
        paramMap.put("auth", auth);
        paramMap.put("role", role);
        String resultStr;
        try {
            resultStr = HttpUtil.post(address + "/wg/admin/register/registerApplicationInterfaceMethod", paramMap, 2000);
        } catch (Exception e) {
            logger.error("应用服务接口注册方法异常，链接资源不可用：{}", address + "/wg/admin/register/registerApplicationInterfaceMethod");
            throw e;
        }
        Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() {});
        logger.info("向网关中心注册应用接口方法服务 systemId：{} interfaceId：{} methodId：{} 注册结果：{}", systemId, interfaceId, methodId, resultStr);
        if (!"0000".equals(result.getCode()) && !"0003".equals(result.getCode()))
            throw new GatewayException("向网关中心注册应用接口方法服务异常 [systemId：" + systemId + "] 、[interfaceId：" + interfaceId + "]、[methodId：]" + methodId + "]");
    }

    public String executeHttp(String uri, String jsonString) throws IOException {
        HttpPost httpPost = new HttpPost();
        httpPost.setURI(URI.create(uri));
        httpPost.addHeader("accept", "*/*");
        httpPost.addHeader("connection", "Keep-Alive");
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        client.close();
        return result;
    }

    public void doRegisterApplicationInterfaceMethod(String address, JSONObject jsonObject){
        try {
            String jsonString = jsonObject.toJSONString();
            String result = executeHttp(address + "/wg/admin/register/registerApplicationInterfaceMethodNew", jsonString);
            logger.info(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void doRegisterEvent(String address, String systemId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);
        String resultStr;
        try {
            resultStr = HttpUtil.post(address + "/wg/admin/register/registerEvent", paramMap, 6000);
        } catch (Exception e) {
            logger.error("应用服务接口事件方法异常，链接资源不可用：{}", address + "/wg/admin/register/registerEvent");
            throw e;
        }
        Result<Boolean> result = JSON.parseObject(resultStr, new TypeReference<Result<Boolean>>() {});
        logger.info("应用服务接口事件方法 systemId：{} 注册结果：{}", systemId, resultStr);
        if (!"0000".equals(result.getCode()))
            throw new GatewayException("向网关中心注册应用接口服务异常 [systemId：" + systemId + "]");
    }


    public List<String> queryGatewayId(String address,String systemId){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);
        try {
            String resultStr = HttpUtil.post(address + "/wg/admin/config/queryGatewayId", paramMap, 6000);
            Result<List<String>> listResult = JSON.parseObject(resultStr, new TypeReference<Result<List<String>>>() {});
            return listResult.getData();
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
